<?php  if (!defined('BASEPATH') || !defined('CRON')) exit('No direct script access allowed');

require_once APPPATH . 'controllers/cron.php';
require_once APPPATH . 'libraries/VideoEntry.php';

/**
 * Получение данных по по партнеркам
 *
 * @author Gennadiy Kozlenko
 */
class Cron_Partners extends Cron {
     
    /**
     * Конструктор класса
     */
    public function __construct() {
        parent::Cron();
        $this->load->config('parser');
        $this->load->model('m_partner');
        $this->load->helper('text');
    }
     
    /**
     * Точка входа
     */
    public function index() {
        $this->load->library('license');
        if (!$this->license->isActivated()) {
            $this->log('Application not activated yet.');
            exit;
        }
        $this->log("Start partners");
        $partners = $this->getPartners();
        if (0 < count($partners)) {
            $this->log('Found ' . count($partners) . ' active video partners');
            foreach ($partners as $partner) {
                // Подгружаем источник видео
                $file = APPPATH . 'libraries/PartnerParser/' . $partner['name'] . '.php';
                if (file_exists($file)) {
                    $this->load->file($file);
                    try {
                        $this->log('Parse ' . $partner['name']);
                        // Создаем объект парсера
                        $class = 'PartnerParser_' . $partner['name'];
                        $parser = new $class();
                        $parser->setIdPartner($partner['id_partner']);
                        $parser->setXmlLink($partner['xml_link']);
                        $parser->setTimeout($this->config->item('parser_xml_timeout'));
                        $parser->parse();
                    } catch (Exception $e) {
                        $this->log('Error: ' . $e->getMessage());
                    }
                }
            }
        }
        $this->log("Stop partners");
    }
    
    /**
     * Get partners
     */
    private function getPartners() {
        $partners = array();
        $this->db->select('id_partner, name')
            ->from('partners')
            ->where('status', 'active')
            ->order_by('position');
        $query = $this->db->get();
        if (0 < $query->num_rows()) {
            foreach ($query->result_array() as $partner) {
                $this->m_partner->set_id($partner['id_partner']);
                if (0 < $this->m_partner->get_id('id_partner')) {
                    $partner['xml_link'] = $this->m_partner->getXmlLink();
                    array_push($partners, $partner);
                }
            }
        }
        return $partners;
    }
     
}
